package com.zlb.app.modules.file.controller;

import cn.hutool.core.util.StrUtil;
import com.zlb.app.common.entity.R;
import com.zlb.app.common.enums.FilePathEnum;
import com.zlb.app.common.strategy.context.UploadStrategyContext;
import com.zlb.app.modules.file.entity.UploadResponse;
import com.zlb.app.utils.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * @Desc 文件服务相关接口
 * @Author zWX1367238
 * @Date 2024-08-16 17:06:46
 **/
@RestController
@RequestMapping("/file")
@Api(tags = "文件服务")
public class FileController {

    @Autowired
    private UploadStrategyContext uploadStrategyContext;

    @PostMapping("/upload")
    @ApiOperation("单个文件上传,folder为文件保存在哪个文件夹下")
    public R<String> upload(@RequestPart("file") MultipartFile file, @RequestParam(value = "folder", required = false) String folder) {
        return R.ok(uploadStrategyContext.upload(file, StrUtil.emptyToDefault(folder, FilePathEnum.COMMON.getPath())));
    }

    @PostMapping("/uploads")
    @ApiOperation("多个文件上传,folder为文件保存在哪个文件夹下")
    public R<List<String>> uploads(@RequestPart("files") MultipartFile[] files, @RequestParam(value = "folder", required = false) String folder) {
        List<String> list = new ArrayList<>();
        for (MultipartFile file : files) {
            list.add(uploadStrategyContext.upload(file, StrUtil.emptyToDefault(folder, FilePathEnum.COMMON.getPath())));
        }
        return R.ok(list);
    }

    @PostMapping("/uploadFile")
    @ApiOperation("单个文件上传,会返回原文件名,folder为文件保存在哪个文件夹下")
    public R<UploadResponse> uploadFile(@RequestPart("file") MultipartFile file, @RequestParam(value = "folder", required = false) String folder) {
        return R.ok(UploadResponse.builder()
                                  .name(FileUtil.removeExtName(file.getOriginalFilename()))
                                  .url(uploadStrategyContext.upload(file, StrUtil.emptyToDefault(folder, FilePathEnum.COMMON.getPath())))
                                  .build());
    }

    @PostMapping("/uploadFiles")
    @ApiOperation("多个文件上传,folder为文件保存在哪个文件夹下")
    public R<List<UploadResponse>> uploadFiles(@RequestPart("files") MultipartFile[] files, @RequestParam(value = "folder", required = false) String folder) {
        List<UploadResponse> list = new ArrayList<>();
        for (MultipartFile file : files) {
            list.add(UploadResponse.builder()
                                   .name(file.getOriginalFilename())
                                   .url(uploadStrategyContext.upload(file, StrUtil.emptyToDefault(folder, FilePathEnum.COMMON.getPath())))
                                   .build());
        }
        return R.ok(list);
    }

}
